﻿using Domain.Entitys.Sinv;
using Domain.IRepositorys.Sinv;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Domain.Entitys.Sinv.Sinv_Sale_Outbound_Info;

namespace EFCore.Repositorys.Sinv
{
    public class Sinv_Sale_ReturnRepository : ISinv_Sale_ReturnRepository
    {
        private readonly MyDbContext myDbContext;

        public Sinv_Sale_ReturnRepository(MyDbContext myDbContext)
        {
            this.myDbContext = myDbContext;
        }

        /// <summary>
        /// 分页条件查询销售退货信息
        /// </summary>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <param name="customerName"></param>
        /// <param name="orderCode"></param>
        /// <returns></returns>
        public List<Sinv_Sale_Return_Info> GetSinv_Sale_Return_Infos(int currentPage, int pageSize, string customerName, string orderCode, int orderStatus, char auditStatus)
        {
            IQueryable<Sinv_Sale_Return> query = myDbContext.Sinv_Sale_Return;
            query = query.Where(sr => sr.Del_Flag == '0').OrderByDescending(sr => sr.Create_Time).ThenByDescending(sr => sr.Update_Time);

            if (!string.IsNullOrEmpty(customerName))
            {
                query = query.Where(sr => sr.Customer_Code.Contains(customerName) || sr.Customer_Name.Contains(customerName));
            }
            if (!string.IsNullOrEmpty(orderCode))
            {
                query = query.Where(sr => sr.Sale_Order_Code.Contains(orderCode));
            }
            if (orderStatus != -1)
            {
                query = query.Where(s => s.Sale_Return_Status == orderStatus);
            }
            if (auditStatus == '0' || auditStatus == '1' || auditStatus == '2')
            {
                query = query.Where(s => s.Sale_Return_Audit_Status == auditStatus);
            }
            if (currentPage != 0 && pageSize != 0)
            {
                query = query.Skip((currentPage - 1) * pageSize).Take(pageSize);
            }
            var result = query
                //.ThenBy(sr => sr.Update_Time)
                .Select(sr => new Sinv_Sale_Return_Info
                {
                    Sale_Return_Id = sr.Sale_Return_Id,
                    Sale_Return_Code = sr.Sale_Return_Code,
                    Sale_Order_Name = sr.Sale_Order_Name,
                    Sale_Order_Code = sr.Sale_Order_Code,
                    Customer_Name = sr.Customer_Name,
                    Customer_Code = sr.Customer_Code,
                    Contacts_Name = sr.Contacts_Name,
                    Contacts_Phone = sr.Contacts_Phone,
                    Sale_Order_Rep_Id = sr.Sale_Order_Rep_Id,
                    Sale_Order_Dept_Id = sr.Sale_Order_Dept_Id,
                    Sale_Return_Audit_By = sr.Sale_Return_Audit_By,
                    Sale_Return_Audit_Time = sr.Sale_Return_Audit_Time,
                    Sale_Return_Audit_Status = sr.Sale_Return_Audit_Status,
                    Sale_Return_Audit_Opinion = sr.Sale_Return_Audit_Opinion,
                    Warehouse_Code = sr.Warehouse_Code,
                    Warehouse_Name = sr.Warehouse_Name,
                    Zone_Code = sr.Zone_Code,
                    Zone_Name = sr.Zone_Name,
                    Sale_Return_Reason = sr.Sale_Return_Reason,
                    Sale_Return_Status = sr.Sale_Return_Status,
                    Sale_Return_Dept_Id = sr.Sale_Return_Dept_Id,
                    Sale_Return_Rep_Id = sr.Sale_Return_Rep_Id,
                    Sale_Return_Store_Time = sr.Sale_Return_Store_Time,
                    Details = sr.Details.Select(details => new Sinv_Sale_Return_Info.Sinv_Sale_Return_Details
                    {
                        Sale_Return_Details_Id = details.Sale_Return_Details_Id,
                        Sale_Return_Id = details.Sale_Return_Id,
                        Sale_Return_Code = details.Sale_Return_Code,
                        Pro_Code = details.Pro_Code,
                        Pro_Brand = details.Pro_Brand,
                        Pro_Name = details.Pro_Name,
                        Measure_Id = details.Measure_Id,
                        Pro_Sale_Qty = details.Pro_Sale_Qty,
                        Pro_Return_Qty = details.Pro_Return_Qty,
                        Pro_Store_Qty = details.Pro_Store_Qty,
                        Pro_Return_Price = details.Pro_Return_Price,
                        Pro_Model = details.Pro_Model,
                    }).ToList()
                }).ToList();
            return result;
        }

        /// <summary>
        /// 添加销售退货信息
        /// </summary>
        /// <param name="sinv_Sale_Return"></param>
        /// <param name="sinv_Sale_Return_Details"></param>
        /// <returns></returns>
        public async Task<int> Sinv_Sale_ReturnAddAsync(Sinv_Sale_Return sinv_Sale_Return, List<Sinv_Sale_Return_Details> sinv_Sale_Return_Details)
        {
            using var transaction = await myDbContext.Database.BeginTransactionAsync();
            try
            {
                //添加销售退货信息
                await myDbContext.AddAsync(sinv_Sale_Return);
                await myDbContext.SaveChangesAsync();

                //添加销售退货明细
                foreach (var item in sinv_Sale_Return_Details)
                {
                    item.Sale_Return_Id = sinv_Sale_Return.Sale_Return_Id;
                    item.Sale_Return_Code = sinv_Sale_Return.Sale_Return_Code;
                }
                await myDbContext.AddRangeAsync(sinv_Sale_Return_Details);
                await myDbContext.SaveChangesAsync();

                //修改预计退货数量
                var orderDetails = await myDbContext.Sinv_Sale_Order_Details
                    .Where(sod => sod.Sale_order_code == sinv_Sale_Return.Sale_Order_Code).ToListAsync();
                foreach (var item in orderDetails)
                {
                    var returnQty = sinv_Sale_Return_Details
                        .Where(srd => srd.Sale_order_details_id == item.Sale_order_details_id)
                        .Sum(srd => srd.Pro_Return_Qty);
                    item.Pro_planned_return_qty += returnQty;
                }
                await myDbContext.SaveChangesAsync();
                await transaction.CommitAsync();
                return 1;
            }
            catch (Exception)
            {
                await transaction.RollbackAsync();
                return 0;
            }
        }

        /// <summary>
        /// 根据销售退货编号查询对应销售退货信息
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public async Task<Sinv_Sale_Return> Sinv_Sale_ReturnByCodeAsync(string code)
        {
            return await myDbContext.Sinv_Sale_Return.FirstOrDefaultAsync(sr => sr.Sale_Return_Code == code);
        }

        /// <summary>
        /// 条件查询销售退货总数
        /// </summary>
        /// <param name="customerName"></param>
        /// <param name="orderCode"></param>
        /// <returns></returns>
        public async Task<int> Sinv_Sale_ReturnCountAsync(string customerName, string orderCode, int orderStatus, char auditStatus)
        {
            IQueryable<Sinv_Sale_Return> query = myDbContext.Sinv_Sale_Return;
            query = query.Where(sr => sr.Del_Flag == '0');
            if (!string.IsNullOrEmpty(customerName))
            {
                query = query.Where(sr => sr.Customer_Code.Contains(customerName) || sr.Customer_Name.Contains(customerName));
            }
            if (!string.IsNullOrEmpty(orderCode))
            {
                query = query.Where(sr => sr.Sale_Order_Code.Contains(orderCode));
            }
            if (orderStatus != -1)
            {
                query = query.Where(s => s.Sale_Return_Status == orderStatus);
            }
            if (auditStatus == '0' || auditStatus == '1' || auditStatus == '2')
            {
                query = query.Where(s => s.Sale_Return_Audit_Status == auditStatus);
            }
            return await query.CountAsync();
        }

        /// <summary>
        /// 修改销售退货信息及其详情
        /// </summary>
        /// <param name="sinv_Sale_Return"></param>
        /// <param name="sinv_Sale_Return_Details"></param>
        /// <returns></returns>
        public async Task<int> Sinv_Sale_ReturnUpdateAsync(Sinv_Sale_Return sinv_Sale_Return, List<Sinv_Sale_Return_Details> sinv_Sale_Return_Details)
        {
            using var transaction = await myDbContext.Database.BeginTransactionAsync();
            try
            {
                //修改销售退货信息
                Sinv_Sale_Return sinv_Sale_Return1 = await myDbContext.Sinv_Sale_Return
                    .FirstOrDefaultAsync(sr => sr.Sale_Return_Id == sinv_Sale_Return.Sale_Return_Id);
                sinv_Sale_Return1.Sale_Return_Code = sinv_Sale_Return.Sale_Return_Code;
                sinv_Sale_Return1.Sale_Order_Name = sinv_Sale_Return.Sale_Order_Name;
                sinv_Sale_Return1.Sale_Order_Code = sinv_Sale_Return.Sale_Order_Code;
                sinv_Sale_Return1.Customer_Name = sinv_Sale_Return.Customer_Name;
                sinv_Sale_Return1.Customer_Code = sinv_Sale_Return.Customer_Code;
                sinv_Sale_Return1.Contacts_Name = sinv_Sale_Return.Contacts_Name;
                sinv_Sale_Return1.Contacts_Phone = sinv_Sale_Return.Contacts_Phone;
                sinv_Sale_Return1.Sale_Order_Rep_Id = sinv_Sale_Return.Sale_Order_Rep_Id;
                sinv_Sale_Return1.Sale_Order_Dept_Id = sinv_Sale_Return.Sale_Order_Dept_Id;
                sinv_Sale_Return1.Warehouse_Code = sinv_Sale_Return.Warehouse_Code;
                sinv_Sale_Return1.Warehouse_Name = sinv_Sale_Return.Warehouse_Name;
                sinv_Sale_Return1.Zone_Code = sinv_Sale_Return.Zone_Code;
                sinv_Sale_Return1.Zone_Name = sinv_Sale_Return.Zone_Name;
                sinv_Sale_Return1.Sale_Return_Reason = sinv_Sale_Return.Sale_Return_Reason;
                sinv_Sale_Return1.Sale_Return_Status = sinv_Sale_Return.Sale_Return_Status;
                sinv_Sale_Return1.Sale_Return_Rep_Id = sinv_Sale_Return.Sale_Return_Rep_Id;
                sinv_Sale_Return1.Sale_Return_Dept_Id = sinv_Sale_Return.Sale_Return_Dept_Id;
                sinv_Sale_Return1.Sale_Return_Store_Time = sinv_Sale_Return.Sale_Return_Store_Time;
                sinv_Sale_Return1.Update_By = sinv_Sale_Return.Update_By;
                sinv_Sale_Return1.Update_Time = sinv_Sale_Return.Update_Time;
                myDbContext.Update(sinv_Sale_Return1);
                await myDbContext.SaveChangesAsync();

                var oldDetails = await myDbContext.Sinv_Sale_Return_Details.
                    Where(srd => srd.Sale_Return_Code == sinv_Sale_Return1.Sale_Return_Code).ToListAsync();
                var toAdd = new List<Sinv_Sale_Return_Details>();//新增明细
                var toUpdate = new List<Sinv_Sale_Return_Details>();//更新明细
                var toDel = new List<int>();//删除明细id
                var netChangeDict = new Dictionary<int, decimal>(); // <sale_order_details_id, 净变化量>

                foreach (var newItem in sinv_Sale_Return_Details)
                {
                    //新记录：无主键或主键不在旧列表中
                    if (newItem.Sale_Return_Details_Id == 0 ||
                        !oldDetails.Any(old => old.Sale_Return_Details_Id == newItem.Sale_Return_Details_Id))
                    {
                        toAdd.Add(newItem);
                    }
                    else
                    {
                        var oldItem = oldDetails.First(old => old.Sale_Return_Details_Id == newItem.Sale_Return_Details_Id);
                        if (IsModified(oldItem, newItem))//检查字段是否有变化
                        {
                            toUpdate.Add(newItem);
                        }
                    }
                }

                toDel = oldDetails.Where(old => !sinv_Sale_Return_Details.Any(newItem => newItem.Sale_Return_Details_Id == old.Sale_Return_Details_Id))
                    .Select(old => old.Sale_Return_Details_Id).ToList();

                // 批量删除旧明细
                if (toDel.Any())
                {
                    var delItems = oldDetails.Where(d => toDel.Contains(d.Sale_Return_Details_Id));
                    myDbContext.RemoveRange(delItems);
                }

                //更新变化的明细
                foreach (var item in toAdd)
                {
                    item.Sale_Return_Code = sinv_Sale_Return1.Sale_Return_Code;
                    item.Sale_Return_Id = sinv_Sale_Return1.Sale_Return_Id;
                    await myDbContext.AddAsync(item);
                }

                //更新变化的明细
                foreach (var updateItem in toUpdate)
                {
                    var existingDetail = oldDetails.FirstOrDefault(d => d.Sale_Return_Details_Id == updateItem.Sale_Return_Details_Id);
                    if (existingDetail != null)
                    {
                        existingDetail.Pro_Return_Qty = updateItem.Pro_Return_Qty;
                        existingDetail.Pro_Store_Qty = updateItem.Pro_Store_Qty;
                        existingDetail.Pro_Return_Price = updateItem.Pro_Return_Price;
                        myDbContext.Update(existingDetail);
                    }
                }
                await myDbContext.SaveChangesAsync(); // 保存明细的更新

                // 处理删除的明细：减少退货量
                foreach (var delItem in oldDetails.Where(d => toDel.Contains(d.Sale_Return_Details_Id)))
                {
                    if (!netChangeDict.ContainsKey(delItem.Sale_order_details_id))
                        netChangeDict[delItem.Sale_order_details_id] = 0;
                    netChangeDict[delItem.Sale_order_details_id] -= delItem.Pro_Return_Qty;
                }

                // 处理新增明细：增加退货量
                foreach (var newItem in toAdd)
                {
                    if (!netChangeDict.ContainsKey(newItem.Sale_order_details_id))
                        netChangeDict[newItem.Sale_order_details_id] = 0;
                    netChangeDict[newItem.Sale_order_details_id] += newItem.Pro_Return_Qty;
                }

                // 处理修改的明细：计算新旧差值
                foreach (var updateItem in toUpdate)
                {
                    var oldQty = oldDetails
                        .FirstOrDefault(old => old.Sale_Return_Details_Id == updateItem.Sale_Return_Details_Id)?
                        .Pro_Return_Qty ?? 0;

                    if (!netChangeDict.ContainsKey(updateItem.Sale_order_details_id))
                        netChangeDict[updateItem.Sale_order_details_id] = 0;

                    netChangeDict[updateItem.Sale_order_details_id] += updateItem.Pro_Return_Qty - oldQty;
                }

                foreach (var (orderDetailId, netChange) in netChangeDict)
                {
                    var orderDetail = await myDbContext.Sinv_Sale_Order_Details
                        .FirstAsync(sod => sod.Sale_order_details_id == orderDetailId);

                    orderDetail.Pro_planned_return_qty += netChange; // 更新累计退货量
                }
                await myDbContext.SaveChangesAsync();

                await transaction.CommitAsync();
                return 1;
            }
            catch (Exception)
            {
                await transaction.RollbackAsync();
                return 0;
            }
        }

        /// <summary>
        /// 检查字段是否修改
        /// </summary>
        /// <param name="oldItem"></param>
        /// <param name="newItem"></param>
        /// <returns></returns>
        private bool IsModified(Sinv_Sale_Return_Details oldItem, Sinv_Sale_Return_Details newItem)
        {
            return oldItem.Pro_Return_Qty != newItem.Pro_Return_Qty ||
                   oldItem.Pro_Return_Price != newItem.Pro_Return_Price ||
                   oldItem.Pro_Store_Qty != newItem.Pro_Store_Qty ||
                   oldItem.Sale_Return_Details_Id == newItem.Sale_Return_Details_Id;
        }

        /// <summary>
        /// 根据销售退货编号查询对应销售退货明细
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public async Task<List<Sinv_Sale_Return_Details>> Sinv_Sale_Return_DetailsByCodeAsync(string code)
        {
            return await myDbContext.Sinv_Sale_Return_Details.Where(srd => srd.Sale_Return_Code == code).ToListAsync();
        }

        /// <summary>
        /// 修改订单审核状态、增加库存、修改销售明细退货数量、修改销售订单状态
        /// </summary>
        /// <param name="sinv_Sale_Return"></param>
        /// <returns></returns>
        public async Task<int> Sinv_Sale_ReturnAuditUpdateAsync(Sinv_Sale_Return sinv_Sale_Return)
        {
            using var transaction = await myDbContext.Database.BeginTransactionAsync();
            try
            {
                //修改销售退货审核状态
                Sinv_Sale_Return sinv_Sale_Return1 = await myDbContext.Sinv_Sale_Return
                    .FirstOrDefaultAsync(sr => sr.Sale_Return_Id == sinv_Sale_Return.Sale_Return_Id);
                sinv_Sale_Return1.Sale_Return_Audit_By = sinv_Sale_Return.Sale_Return_Audit_By;
                sinv_Sale_Return1.Sale_Return_Audit_Time = sinv_Sale_Return.Sale_Return_Audit_Time;
                sinv_Sale_Return1.Sale_Return_Audit_Status = sinv_Sale_Return.Sale_Return_Audit_Status;
                sinv_Sale_Return1.Sale_Return_Audit_Opinion = sinv_Sale_Return.Sale_Return_Audit_Opinion;

                myDbContext.Sinv_Sale_Return.Update(sinv_Sale_Return1);

                List<Sinv_Sale_Return_Details> sinv_Sale_Return_Details = myDbContext.Sinv_Sale_Return_Details
                    .Where(srd => srd.Sale_Return_Id == sinv_Sale_Return1.Sale_Return_Id).ToList();
                if (sinv_Sale_Return1.Sale_Return_Audit_Status == '1')
                {
                    await UpdateInventoryAndOrdersAsync(sinv_Sale_Return1, sinv_Sale_Return_Details);
                }
                else if (sinv_Sale_Return1.Sale_Return_Audit_Status == '2')
                {
                    await UpdateOrdersAsync(sinv_Sale_Return_Details);
                }
                await myDbContext.SaveChangesAsync();
                await transaction.CommitAsync();
                return 1;
            }
            catch (Exception)
            {
                await transaction.RollbackAsync();
                return 0;
            }
        }

        /// <summary>
        /// 减少销售明细预计退货数量
        /// </summary>
        /// <param name="sinv_Sale_Return_Details"></param>
        /// <returns></returns>
        private async Task UpdateOrdersAsync(List<Sinv_Sale_Return_Details> sinv_Sale_Return_Details)
        {
            var detailIds = sinv_Sale_Return_Details.Select(d => d.Sale_order_details_id).Distinct().ToList();
            var orderDateils = await myDbContext.Sinv_Sale_Order_Details
                .Where(sod => detailIds.Contains(sod.Sale_order_details_id))
                .ToDictionaryAsync(s => s.Sale_order_details_id);
            //更新明细预计退货数
            foreach (var item in sinv_Sale_Return_Details)
            {
                orderDateils[item.Sale_order_details_id].Pro_planned_return_qty -= item.Pro_Return_Qty;
            }
        }

        /// <summary>
        /// 增加库存、修改销售明细退货数量、修改销售订单状态
        /// </summary>
        /// <param name="sinv_Sale_Return"></param>
        /// <param name="sinv_Sale_Return_Details"></param>
        /// <returns></returns>
        private async Task UpdateInventoryAndOrdersAsync(Sinv_Sale_Return sinv_Sale_Return, List<Sinv_Sale_Return_Details> sinv_Sale_Return_Details)
        {
            //聚合待更新数据
            var detailIds = sinv_Sale_Return_Details.Select(d => d.Sale_order_details_id).Distinct().ToList();
            var proCodes = sinv_Sale_Return_Details.Select(d => d.Pro_Code).Distinct().ToList();

            //批量预加载 ToDictionaryAsync将数据库查询结果集​​异步加载​​并转换为字典
            var stocks = await myDbContext.inv_stock
                .Where(s => proCodes.Contains(s.pro_code)
                && s.Warehouse_Code == sinv_Sale_Return.Warehouse_Code
                && s.Zone_Code == sinv_Sale_Return.Zone_Code)
                .ToListAsync();
            var stockGroups = stocks
                .GroupBy(s => s.pro_code)
                .ToDictionary(g => g.Key, g => g.ToList());
            var orderDateils = await myDbContext.Sinv_Sale_Order_Details
                .Where(sod => detailIds.Contains(sod.Sale_order_details_id))
                .ToDictionaryAsync(s => s.Sale_order_details_id);

            var saleOrder = await myDbContext.Sinv_Sale_Order
                .FirstOrDefaultAsync(o => o.Sale_order_code == sinv_Sale_Return.Sale_Order_Code);

            //var stocksById = stocks.ToDictionary(s => s.stock_id);
            //// 字典2：以pro_code为键映射到stock_id
            //var stockIdByProCode = stocks.ToDictionary(s => s.pro_code, s => s.stock_id);

            //如果销售订单还没有出库则不增加库存
            if (saleOrder.Sale_order_status != 0)
            {
                foreach (var item in sinv_Sale_Return_Details)
                {
                    if (stockGroups.TryGetValue(item.Pro_Code, out var stockList) && stockList.Any())
                    {
                        var stock = stockList.First(); // 默认选择第一条库存记录
                        stock.stock_numder += item.Pro_Return_Qty;
                        myDbContext.Entry(stock).State = EntityState.Modified;

                    }
                }
            }

            //foreach (var item in sinv_Sale_Return_Details)
            //{
            //    stocks[item.Pro_Code].stock_numder += item.Pro_Return_Qty;
            //    myDbContext.Entry(stocks[item.Pro_Code]).State = EntityState.Modified; // 显式标记
            //}

            //var stocks = await myDbContext.inv_stock
            //    .Where(s => proCodes.Contains(s.pro_code)
            //    && s.Warehouse_Code == sinv_Sale_Return.Warehouse_Code
            //    && s.Zone_Code == sinv_Sale_Return.Zone_Code)
            //    .ToDictionaryAsync(s => s.pro_code);

            //var orderDateils = await myDbContext.Sinv_Sale_Order_Details
            //    .Where(sod => detailIds.Contains(sod.Sale_order_details_id))
            //    .ToDictionaryAsync(s => s.Sale_order_details_id);

            //var saleOrder = await myDbContext.Sinv_Sale_Order
            //    .FirstOrDefaultAsync(o => o.Sale_order_code == sinv_Sale_Return.Sale_Order_Code);

            ////如果销售订单还没有出库则不增加库存
            //if (saleOrder.Sale_order_status != 0)
            //{
            //    //增加库存
            //    foreach (var item in sinv_Sale_Return_Details)
            //    {
            //        stocks[item.Pro_Code].stock_numder += item.Pro_Return_Qty;
            //        myDbContext.Entry(stocks[item.Pro_Code]).State = EntityState.Modified; // 显式标记
            //    }
            //}

            //更新明细退货数
            foreach (var item in sinv_Sale_Return_Details)
            {
                orderDateils[item.Sale_order_details_id].Pro_return_qty += item.Pro_Return_Qty;
                orderDateils[item.Sale_order_details_id].Pro_planned_return_qty -= item.Pro_Return_Qty;
                if (orderDateils[item.Sale_order_details_id].Pro_return_qty <= orderDateils[item.Sale_order_details_id].Pro_outbound_qty)
                {
                    orderDateils[item.Sale_order_details_id].Pro_outbound_qty -= item.Pro_Return_Qty;
                }
            }

            if (saleOrder != null)
            {
                bool allCompleted = false;
                bool anyOutbound = false;
                bool anyReturn = false;
                bool anyPlannedOutbound = false;
                bool anyComplete = false;
                foreach (var detail in saleOrder.Details)
                {
                    // 计算净出库量 = 出库量 - 退货量
                    decimal netOutbound = detail.Pro_outbound_qty - detail.Pro_return_qty;

                    //检查是否全部退货：部分退货
                    if (netOutbound < detail.Pro_sale_qty)
                        allCompleted = true;

                    // 检查是否有出库
                    if (detail.Pro_outbound_qty > detail.Pro_return_qty)
                        anyOutbound = true;

                    //检查是否全部退货
                    //if (detail.Pro_return_qty == detail.Pro_sale_qty)
                    //    anyReturn = true;

                    //检查是否还有出库
                    if (detail.Pro_outbound_qty == detail.Pro_return_qty)
                        anyPlannedOutbound = true;

                    //检查是否已完成
                    if (detail.Pro_sale_qty == (detail.Pro_outbound_qty + detail.Pro_return_qty))
                        anyComplete = true;
                }

                // 更新订单状态
                if (anyPlannedOutbound)
                {
                    //待出库
                    saleOrder.Sale_order_status = 0;
                }
                else if (anyOutbound)
                {
                    //部分出库
                    saleOrder.Sale_order_status = 1;
                }
                else if (anyComplete)
                {
                    //全部退货
                    saleOrder.Sale_order_status = 4;
                }
                else if (allCompleted)
                {
                    //部分退货
                    saleOrder.Sale_order_status = 3;
                }
                //else if (anyReturn)
                //{
                //    //全部退货
                //    saleOrder.Sale_order_status = 4;
                //}

                myDbContext.Update(saleOrder);
            }
        }

        /// <summary>
        /// 逻辑删除销售退货信息并修改销售明细预计退货数量
        /// </summary>
        /// <param name="sinv_Sale_Return"></param>
        /// <returns></returns>
        public async Task<int> Sinv_Sale_ReturnDelAsync(Sinv_Sale_Return sinv_Sale_Return)
        {
            using var transaction = await myDbContext.Database.BeginTransactionAsync();
            try
            {
                Sinv_Sale_Return sinv_Sale_Return1 = await myDbContext.Sinv_Sale_Return
                    .FirstOrDefaultAsync(sr => sr.Sale_Return_Id == sinv_Sale_Return.Sale_Return_Id);
                sinv_Sale_Return1.Del_Flag = sinv_Sale_Return.Del_Flag;
                myDbContext.Sinv_Sale_Return.Update(sinv_Sale_Return1);

                List<Sinv_Sale_Return_Details> sinv_Sale_Return_Details = await myDbContext.Sinv_Sale_Return_Details
                    .Where(srd => srd.Sale_Return_Id == sinv_Sale_Return1.Sale_Return_Id).ToListAsync();
                await UpdateOrdersAsync(sinv_Sale_Return_Details);
                await myDbContext.SaveChangesAsync();

                await transaction.CommitAsync();
                return 1;
            }
            catch (Exception)
            {
                await transaction.RollbackAsync();
                return 0;
            }
        }

        public Task<Sinv_Sale_Return_Details> Sinv_Sale_Return_DetailsFillAsync(string saleCode, int currentPage, int pageSize)
        {
            throw new NotImplementedException();
            //IQueryable<Sinv_Sale_Return_Details> sinv_Sale_Return_Details = myDbContext.Sinv_Sale_Return_Details;
            //sinv_Sale_Return_Details = sinv_Sale_Return_Details.Where(srd => srd.);
        }

        public Task<int> Sinv_Sale_Return_DetailsFillCountAsync(string saleCode)
        {
            throw new NotImplementedException();
        }
    }
}
